#include "menu.h"
#include <limits> // 用于输入错误处理

// 主菜单
void Menu::showMainMenu() {
    system("cls"); // 清屏（Windows可用，Linux/macOS需改为"clear"）
    std::cout << "============ 玩具出租管理系统 ============" << std::endl;
    std::cout << "1. 用户管理" << std::endl;
    std::cout << "2. 玩具租赁" << std::endl;
    std::cout << "3. 玩具管理" << std::endl;
    std::cout << "4. 查询统计" << std::endl;
    std::cout << "5. 退出系统" << std::endl;
    std::cout << "=====================================" << std::endl;
    std::cout << "请输入您的选择: ";
}

// 用户管理菜单（入口函数）
void Menu::showUserMenu(UserManager& manager) {
    int choice;
    do {
        system("cls");
        std::cout << "============ 用户管理系统 ============" << std::endl;
        std::cout << "1. 添加用户" << std::endl;
        std::cout << "2. 查询用户" << std::endl;
        std::cout << "3. 更新用户" << std::endl;
        std::cout << "4. 删除用户" << std::endl;
        std::cout << "5. 显示所有用户" << std::endl;
        std::cout << "6. 返回主菜单" << std::endl;
        std::cout << "===================================" << std::endl;
        std::cout << "请输入您的选择: ";

        choice = getValidIntegerInput("", 1, 6); // 限制1 - 6

        switch (choice) {
            case 1: handleAddUser(manager); break;
            case 2: handleQueryUser(manager); break;
            case 3: handleUpdateUser(manager); break;
            case 4: handleDeleteUser(manager); break;
            case 5: handleDisplayAllUsers(manager); break;
            case 6: std::cout << "返回主菜单..." << std::endl; break;
            default: std::cout << "无效选择，请重试！" << std::endl;
        }

        if (choice != 6) {
            std::cout << "按任意键继续...";
            std::cin.ignore(); // 清除输入缓冲区
            std::cin.get();
        }
    } while (choice != 6);
}

// 添加用户（带输入验证和ID冲突检查）
void Menu::handleAddUser(UserManager& manager) {
    system("cls");
    std::cout << "======= 添加新用户 =======" << std::endl;

    int id = getValidIntegerInput("请输入用户ID（正整数）: ", 1);
    if (manager.readUser(id)) { // 检查ID是否已存在
        std::cout << "错误：该ID已被使用！" << std::endl;
        return;
    }

    std::string name = getNonEmptyStringInput("请输入姓名: ");
    std::string password = getNonEmptyStringInput("请输入密码: ");

    std::cout << "选择用户类型：" << std::endl;
    std::cout << "1. 普通客户（最多租赁3个玩具，租期7天）" << std::endl;
    std::cout << "2. VIP客户（最多租赁5个玩具，租期14天）" << std::endl;
    std::cout << "3. 管理员（后台管理权限）" << std::endl;
    std::cout << "4. 租赁员（处理租赁业务）" << std::endl;
    int type = getValidIntegerInput("请输入类型（1 - 4）: ", 1, 4);

    User* newUser = nullptr;
    switch (type) {
        case 1: newUser = new RegularCustomer(id, name, password); break;
        case 2: newUser = new VIPCustomer(id, name, password); break;
        case 3: newUser = new Admin(id, name, password); break;
        case 4: newUser = new RentalStaff(id, name, password); break;
    }

    manager.createUser(newUser);
    std::cout << "用户添加成功！" << std::endl;
}

// 查询用户（显示详细信息）
void Menu::handleQueryUser(UserManager& manager) {
    system("cls");
    std::cout << "======= 查询用户 =======" << std::endl;
    int id = getValidIntegerInput("请输入要查询的用户ID: ");
    User* user = manager.readUser(id);

    if (!user) {
        std::cout << "未找到该用户！" << std::endl;
        return;
    }

    std::cout << "\n用户详细信息：" << std::endl;
    user->displayInfo();

    // 显示租赁权限（仅客户）
    if (user->getType() == "RegularCustomer" || user->getType() == "VIPCustomer") {
        std::cout << "租赁限制：最多可租 " << user->getMaxRentCount()
                  << " 个玩具，租期最长 " << user->getMaxRentDuration() << " 天" << std::endl;
    }
}

// 更新用户（支持单独更新姓名或密码）
void Menu::handleUpdateUser(UserManager& manager) {
    system("cls");
    std::cout << "======= 更新用户信息 =======" << std::endl;
    int id = getValidIntegerInput("请输入要更新的用户ID: ");
    User* user = manager.readUser(id);

    if (!user) {
        std::cout << "未找到该用户！" << std::endl;
        return;
    }

    std::cout << "当前用户信息：" << std::endl;
    user->displayInfo();

    std::cout << "\n选择更新项：" << std::endl;
    std::cout << "1. 更新姓名" << std::endl;
    std::cout << "2. 更新密码" << std::endl;
    std::cout << "3. 取消更新" << std::endl;
    int choice = getValidIntegerInput("请选择（1 - 3）: ", 1, 3);

    if (choice == 3) return;

    std::string newVal = (choice == 1) ?
        getNonEmptyStringInput("请输入新姓名: ") :
        getNonEmptyStringInput("请输入新密码: ");

    if (choice == 1) user->setName(newVal);
    else user->setPassword(newVal);

    manager.updateUser(id, user->getName(), user->getPassword());
    std::cout << "更新成功！" << std::endl;
}

// 删除用户（带确认提示）
void Menu::handleDeleteUser(UserManager& manager) {
    system("cls");
    std::cout << "======= 删除用户 =======" << std::endl;
    int id = getValidIntegerInput("请输入要删除的用户ID: ");
    User* user = manager.readUser(id);

    if (!user) {
        std::cout << "未找到该用户！" << std::endl;
        return;
    }

    std::cout << "确认删除以下用户？（Y/N）" << std::endl;
    user->displayInfo();
    char confirm;
    std::cin >> confirm;

    if (tolower(confirm) == 'y') {
        manager.deleteUser(id);
        std::cout << "用户删除成功！" << std::endl;
    } else {
        std::cout << "删除操作已取消。" << std::endl;
    }
}

// 显示所有用户（带分页和格式优化）
void Menu::handleDisplayAllUsers(UserManager& manager) {
    system("cls");
    std::cout << "======= 所有用户列表 =======" << std::endl;
    if (manager.readUser(0)) { // 假设ID从1开始，0无效
        std::cout << "当前没有用户记录。" << std::endl;
        return;
    }

    manager.displayAllUsers(); // 调用UserManager的显示函数

    // 补充显示租赁权限（如果需要）
    // （可根据用户类型循环添加额外信息）
}

// 输入验证工具函数
int Menu::getValidIntegerInput(const std::string& prompt, int min, int max) {
    int value;
    while (true) {
        std::cout << prompt;
        if (std::cin >> value) {
            if ((min == -1 || value >= min) && (max == -1 || value <= max)) {
                std::cin.ignore(); // 清除缓冲区剩余内容
                return value;
            }
            std::cout << "输入范围应为 " << (min != -1 ? std::to_string(min) : "无下限")
                      << " 到 " << (max != -1 ? std::to_string(max) : "无上限") << std::endl;
        } else {
            std::cout << "请输入有效整数！" << std::endl;
            std::cin.clear();
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        }
    }
}

std::string Menu::getNonEmptyStringInput(const std::string& prompt) {
    std::string value;
    while (true) {
        std::cout << prompt;
        std::getline(std::cin, value);
        if (!value.empty()) {
            return value;
        }
        std::cout << "输入不能为空！" << std::endl;
    }
}

// 显示玩具管理子菜单
void Menu::displayToyManagementMenu() {
    std::cout << "===== 玩具管理 =====" << std::endl;
    std::cout << "1. 玩具增加" << std::endl;
    std::cout << "2. 玩具删除" << std::endl;
    std::cout << "3. 玩具修改" << std::endl;
    std::cout << "4. 玩具查询" << std::endl;
    std::cout << "5. 返回上级" << std::endl;
    std::cout << "==================" << std::endl;
    std::cout << "请选择操作（1 - 5）：";
}

// 处理玩具管理子菜单选择
void Menu::handleToyManagementMenu(ToyManager& manager) {
    int choice;
    bool running = true;

    while (running) {
        displayToyManagementMenu();
        std::cin >> choice;

        // 清屏操作
#ifdef _WIN32
        system("cls");
#else
        system("clear");
#endif

        switch (choice) {
            case 1:
                addToy(manager);
                break;
            case 2:
                deleteToy(manager);
                break;
            case 3:
                modifyToy(manager);
                break;
            case 4:
                searchToy(manager);
                break;
            case 5:
                running = false;
                break;
            default:
                std::cout << "无效的选择，请重新输入！" << std::endl;
                break;
        }

        if (running) {
            std::cout << "按回车键继续...";
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
            std::cin.get();
        }
    }
}

// 增加玩具
void Menu::addToy(ToyManager& manager) {
    int id;
    std::string name, type;
    double price;
    int total, available;

    std::cout << "请输入玩具ID: ";
    std::cin >> id;
    std::cout << "请输入玩具名称: ";
    std::cin.ignore();
    std::getline(std::cin, name);
    std::cout << "请输入玩具类型: ";
    std::getline(std::cin, type);
    std::cout << "请输入玩具出租价格: ";
    std::cin >> price;
    std::cout << "请输入玩具总数: ";
    std::cin >> total;
    std::cout << "请输入玩具可用数量: ";
    std::cin >> available;

    Toy newToy(id, name, type, price, total, available);
    manager.createToy(newToy);
    std::cout << "玩具添加成功！" << std::endl;
}

// 删除玩具
void Menu::deleteToy(ToyManager& manager) {
    int id;
    std::cout << "请输入要删除的玩具ID: ";
    std::cin >> id;

    Toy* toy = manager.readToy(id);
    if (toy) {
        manager.deleteToy(id);
        std::cout << "玩具删除成功！" << std::endl;
    } else {
        std::cout << "未找到该玩具ID，删除失败！" << std::endl;
    }
}

// 修改玩具
void Menu::modifyToy(ToyManager& manager) {
    int id;
    std::cout << "请输入要修改的玩具ID: ";
    std::cin >> id;

    Toy* toy = manager.readToy(id);
    if (toy) {
        std::string name, type;
        double price;
        int total, available;

        std::cout << "请输入新的玩具名称（留空则不修改）: ";
        std::cin.ignore();
        std::getline(std::cin, name);
        if (!name.empty()) {
            toy->setName(name);
        }
        std::cout << "请输入新的玩具类型（留空则不修改）: ";
        std::getline(std::cin, type);
        if (!type.empty()) {
            toy->setType(type);
        }
        std::cout << "请输入新的玩具出租价格（-1 则不修改）: ";
        std::cin >> price;
        if (price != -1) {
            toy->setPrice(price);
        }
        std::cout << "请输入新的玩具总数（-1 则不修改）: ";
        std::cin >> total;
        if (total != -1) {
            toy->setTotal(total);
        }
        std::cout << "请输入新的玩具可用数量（-1 则不修改）: ";
        std::cin >> available;
        if (available != -1) {
            toy->setAvailable(available);
        }

        manager.updateToy(id, *toy);
        std::cout << "玩具修改成功！" << std::endl;
    } else {
        std::cout << "未找到该玩具ID，修改失败！" << std::endl;
    }
}

// 查询玩具
void Menu::searchToy(ToyManager& manager) {
    std::string keyword;
    std::cout << "请输入查询关键词: ";
    std::cin.ignore();
    std::getline(std::cin, keyword);

    std::vector<Toy> results = manager.searchToys(keyword);
    if (results.empty()) {
        std::cout << "未找到相关玩具！" << std::endl;
    } else {
        std::cout << "查询结果如下：" << std::endl;
        for (const auto& toy : results) {
            toy.displayInfo();
        }
    }
}

// 处理主菜单选择
void Menu::handleMainMenu(UserManager& userManager, ToyManager& toyManager) {
    int choice;
    bool running = true;

    while (running) {
        showMainMenu();
        std::cin >> choice;

        // 清屏操作
#ifdef _WIN32
        system("cls");
#else
        system("clear");
#endif

        switch (choice) {
            case 1:
                showUserMenu(userManager);
                break;
            case 2:
                std::cout << "玩具租赁功能待实现..." << std::endl;
                break;
            case 3:
                handleToyManagementMenu(toyManager);
                break;
            case 4:
                std::cout << "查询统计功能待实现..." << std::endl;
                break;
            case 5:
                std::cout << "退出系统..." << std::endl;
                running = false;
                break;
            default:
                std::cout << "无效的选择，请重新输入！" << std::endl;
                break;
        }

        if (running) {
            std::cout << "按回车键继续...";
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
            std::cin.get();
        }
    }
}    